import { useState } from "react"
import { useNavigate, Outlet, useLocation } from 'react-router-dom'
import styles from '@/App.module.scss'
import { ConfigProvider, theme, Col, Row, Switch, Menu, Dropdown, Popover, MenuProps, Input, message, Form, Modal, Button } from "antd"
import { useSelector, useDispatch } from 'react-redux'
import { setTheme } from "@/store/Appstore/RootStore"
import { AppstoreOutlined, LogoutOutlined, QqOutlined, HomeOutlined, UserOutlined, LaptopOutlined, DownOutlined, SunOutlined, MoonOutlined, LockOutlined } from '@ant-design/icons';
import { HappyProvider } from '@ant-design/happy-work-theme';
import { Creact_User, testapi, Forget_pass } from "@/apis/user"
import type { AppDispatch } from "@/store"
import locale from 'antd/locale/zh_CN';
import { visitweb } from '@/apis/admin/echar'
import dayjs from "dayjs"
import { searchfood } from "@/apis/foods"
import { useEffect } from "react"
import { register } from "@/apis/admin/echar"
dayjs.locale('zh-cn');
import { axios_user_login, axios_user_loginOut } from "@/store/Userstore/UserStore"
function App() {
  let timer: any = null
  const [form] = Form.useForm();
  const [resqqnum, setreqqnum] = useState('')
  const [codeUrl, setcodeUrl] = useState('http://127.0.0.1:3001/user/code')
  const location = useLocation().pathname
  const thems = useSelector((state: any) => state.Appstore.theme)
  const userinfo = useSelector((state: any) => state.UserStore.userinfo)
  const dispatcch = useDispatch<AppDispatch>()
  const navigate = useNavigate()
  const [search1, setsearch1] = useState("")
  const [searchList, setsearchList1] = useState<any>([])

  useEffect(() => {
    visitweb()
  }, [])
  //搜索
  const onPressEnter = (e: any) => {
    if (e.target.value || searchList.length !== 0) {
      console.log(searchList)
      searchList[0]._id && navigate(`/detaile/${searchList[0]._id}`)
    }
  }
  const onChange1 = async (e: any) => {
    clearTimeout(timer)
    if (e.target.value == "") {
      setsearchList1([])
      setsearch1(e.target.value)
      return
    }
    setsearch1(e.target.value)
    timer = setTimeout(async () => {
      const result = await searchfood(e.target.value)
      setsearchList1(result.data)
      console.log(result)
    }, 200);


  }
  const onfocus = async (e: any) => {
    if (e.target.value) {
      const result = await searchfood(e.target.value)
      setsearchList1(result.data)
    }

  }
  //搜索
  const onChange = (_: boolean) => {
    dispatcch(setTheme())
  }

  const items1 = [
    {
      label: '首页',
      key: '/home',
      icon: <HomeOutlined />,

    },
    {
      label: '分类',
      key: '/category',
      icon: <AppstoreOutlined />,

    },
    {
      label: '个人资料',
      key: '/user',
      icon: <UserOutlined />,
    },
    {
      label: "后台",
      key: '/login',
      icon: <LaptopOutlined />
    }

  ];
  const items = [
    {
      key: '1',
      label: (
        <div onClick={() => navigate('/home')}>
          首页
        </div>
      ),
    },
    {
      key: '2',
      label: (
        <div onClick={() => navigate('/category')}>
          分类
        </div>
      ),

    },

    {
      key: '3',
      label: (
        <div onClick={() => navigate('/user')} >
          个人资料
        </div>
      ),

    },
    {
      key: "4",
      label: (
        <div onClick={() => navigate('/login')} >
          后台
        </div>
      ),
    }
  ]

  const onClick: MenuProps['onClick'] = (e) => {
    navigate(e.key)
  };
  //登录
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isLogin, setisLogin] = useState(true);
  const [forgetOpen, setForgetOpen] = useState(false);
  const hide = () => {
    setreqqnum('')
    setForgetOpen(false);
  };
  const resetpass = async () => {
    const res = await Forget_pass(resqqnum)

    if (res.status === 200) {
      message.success("重置成功")
      setreqqnum('')
      setForgetOpen(false);
    }

  }
  const handleOpenChange = (newOpen: boolean) => {
    setForgetOpen(newOpen);
  };

  const tologin = async () => {
    setcodeUrl('http://127.0.0.1:3001/user/code' + '?' + Date.now())
    setIsModalOpen(true)
  }


  const handleCancel = () => {
    setIsModalOpen(false);
  }
  //登录
  const onFinish = async (e: any) => {

    if (isLogin) {
      console.log("登录")
      dispatcch(axios_user_login(e)).then((e) => {
        console.log(e, ';ooo')
        message.success("登录成功")
        setIsModalOpen(false);
        form.resetFields();
      }).catch(() => {
      })

    } else {
      const res = await Creact_User(e)
      if (res.status === 200) {
        message.success("注册成功")
        register()
        setIsModalOpen(false);
        form.resetFields();
      }
      if (res.status === 423) {
        message.error("账号已存在/qq已被绑定")
      }

    }

  }
  //退出登录
  const loginOut = async () => {
    dispatcch(axios_user_loginOut())
  }
  const onFinishFailed = (e: any) => {
    console.log(e, '222')
    message.error("校验未通过")
  }
  const validatePhone = (_: any, value: string) => {
    const phoneRegex = /^\d{6,10}$/;
    if (!phoneRegex.test(value)) {
      return Promise.reject('请输入6-10位数字!');
    }
    return Promise.resolve();
  };
  return (
    <ConfigProvider
      locale={locale}
      theme={{
        algorithm: thems ? theme.defaultAlgorithm : theme.darkAlgorithm,
        components: {
          Switch: {
            colorPrimary: "orange",
            colorPrimaryHover: "orange"
          }
        },
      }}
    >
      <div className={`${thems ? styles.R_light : styles.R_dark}`} style={{ minHeight: '100vh' }}>
        <Row justify={"center"} style={{ background: thems ? 'rgba(255,255,255,0.7)' : 'rgba(0,0,0,0.8)', color: thems ? 'black' : 'white' }}>
          <Col xs={0} sm={0} md={5} lg={5} >
            <p className={styles.logos}>
              <span>
                亿点美味
              </span></p>
          </Col>
          <Col xs={0} sm={17} md={14} lg={14} >
            <Menu style={{ background: thems ? 'rgba(255,255,255,0.7)' : 'rgba(0,0,0,0.8)', }} onClick={onClick} selectedKeys={[location]} mode="horizontal" items={items1} />
          </Col>
          <Col xs={0} sm={7} md={5} lg={5} >
            <div style={{ display: "flex", alignItems: "center", justifyContent: 'space-around', height: '100%' }}>
              <HappyProvider>

                <Switch checkedChildren={<SunOutlined />} unCheckedChildren={<MoonOutlined />} defaultChecked={thems} onChange={onChange} />
              </HappyProvider>

              <div className={styles.login} >
                {
                  userinfo.username ? <div onClick={loginOut} style={{ display: "flex", alignItems: "center" }}>退出< LogoutOutlined style={{ marginLeft: "10px" }} /> </div> : <p onClick={tologin}>登录</p>
                }

              </div>
            </div>
          </Col>
          <Col xs={24} sm={0} md={0} lg={0} style={{ justifyContent: "space-between" }}>
            <div className={styles.mobile}>
              <Dropdown menu={{ items }}>
                <div style={{ color: thems ? 'black' : 'white' }}>
                  菜单
                  <DownOutlined />
                </div>
              </Dropdown>

              <div style={{ width: "50%", position: "relative", }}>
                <Input onBlur={() => {
                  setTimeout(() => {
                    console.log("对对")
                    setsearchList1([])
                  }, 100);
                }} onPressEnter={onPressEnter} onFocus={onfocus} value={search1} onChange={onChange1} style={{ width: "100%" }} />

                {
                  searchList.length !== 0 ? <div style={{ width: "100%", background: thems ? 'rgba(255,255,255,0.8)' : 'rgba(0,0,0,0.6)', position: "absolute", zIndex: 10, maxHeight: '150px', overflowY: "scroll" }}>

                    {
                      searchList.map(((item: any) => {

                        return <p onClick={() => {
                          navigate(`/detaile/${item._id}`)
                        }} className={thems ? styles.idhover : styles.idhover2} style={{ textAlign: "center", padding: "5px 0", }} key={item._id}>{item.title}</p>
                      }))
                    }
                  </div> : ''
                }

              </div>

              <HappyProvider>

                <Switch checkedChildren={<SunOutlined />} unCheckedChildren={<MoonOutlined />} defaultChecked onChange={onChange} />
              </HappyProvider>
              <div className={styles.login} >
                {
                  userinfo.username ? <div onClick={loginOut} style={{ display: "flex", alignItems: "center" }}>退出< LogoutOutlined style={{ marginLeft: "10px" }} /> </div> : <p onClick={tologin}>登录</p>
                }

              </div>
            </div>
          </Col>
        </Row>


        <Row justify={"center"} style={{ color: thems ? 'black' : 'white' }}>

          <div style={{ width: "100%" }}>

            <Outlet></Outlet>

          </div>
        </Row>
      </div>

      {/* 登录 */}

      <Modal title={isLogin ? '登录' : "注册"} style={{ maxWidth: 300 }} open={isModalOpen} onCancel={handleCancel} footer={null}>

        <Form
          form={form}

          name="login"
          className="login-form"
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          style={{ maxWidth: 300 }}
        >
          <Form.Item
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 19 }}
            name="username"
            label="账号"
            rules={[{ required: true, message: '长度在2-7', max: 7, min: 2 }]}
          >
            <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="账号" />
          </Form.Item>
          <Form.Item
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 19 }}
            name="password"
            label="密码"
            rules={[{ required: true, message: '至少三位', min: 3 }]}
          >
            <Input
              prefix={<LockOutlined className="site-form-item-icon" />}
              autoComplete="off"
              type="password"
              placeholder="密码"
            />
          </Form.Item>
          {
            isLogin ? '' : <Form.Item
              labelCol={{ span: 5 }}
              wrapperCol={{ span: 19 }}
              name="qqnumber"
              label="QQ"

              rules={[{ required: true, message: "" }, {
                validator: validatePhone,
              },]}
            >
              <Input prefix={<QqOutlined className="site-form-item-icon" />} />
            </Form.Item>
          }
          <Form.Item
            wrapperCol={{ span: 24 }}
            name="code"

            rules={[{ required: true, message: '请输入计算结果' }]}
          >
            <div className={styles.code} style={{ display: 'flex', justifyContent: "space-between", width: "100%" }}>
              <Input


                placeholder="计算结果"
              />
              <img onClick={() => {
                setcodeUrl('http://127.0.0.1:3001/user/code' + '?' + Date.now())
              }} src={codeUrl} alt="" />
            </div>
          </Form.Item>
          <Form.Item
            wrapperCol={{ span: 22 }}
          >
            <Button type="primary" htmlType="submit" style={{ width: "100%" }} className="login-form-button">
              {isLogin ? "登录" : "注册"}
            </Button>
            <div style={{ display: 'flex', justifyContent: "space-between", marginTop: "10px" }}>
              <a onClick={() => {
                testapi()
                form.resetFields();
                setisLogin(!isLogin)
              }
              }>{isLogin ? '注册' : '登录'}</a>
              <Popover
                content={<div>
                  <Input value={resqqnum} onChange={(e) => setreqqnum(e.target.value)} />
                  <div style={{ display: "flex", justifyContent: "space-between" }}>
                    <a onClick={hide}>关闭</a>
                    <a onClick={resetpass}>重置</a>
                  </div>
                </div>}
                title="输入qq重置密码123456"
                trigger="click"
                open={forgetOpen}
                onOpenChange={handleOpenChange}
              >
                <a className="login-form-forgot">
                  忘记密码?
                </a>

              </Popover>

            </div>
          </Form.Item>
        </Form>
      </Modal>



    </ConfigProvider>
  )
}

export default App
